<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use \App\Home\Protype;
use \App\Home\Course;
use \App\Home\Lession;
use \App\Admin\Live;
use \App\Home\Profession;
use \App\Home\Member_cart;
use \App\Home\Performer;
use Auth;
use Input;
use Crawler;

class IndexController extends Controller
{
	public function index(){
		return view('home.index.index');
	}

	//获取左侧导航分类
	public function getBannerNavLeft(){
		$Top_data = Protype::orderBy('sort','desc') -> with('rel_profession') -> where('status','2') -> limit('8') -> get();
		$Two_data = Course::select('id','course_name','type','profession_id') -> where('click_num','>=','200') -> orderBy('sort','desc') -> get();
		$data = compact('Top_data','Two_data');
		return response() -> json($data);
	}

	//获取轮播图
	public function getSliderBannerNav(){
		$data = Course::select('id','description','big_banner_img') -> where('is_show_PC','1') -> orderBy('sort','desc') -> limit('7') -> get();
		return response() -> json($data);
	}

	//获取培训课程
	public function getCourseIntroductionList(){
		$data = Course::select('id','course_name','description','cover_img') -> orderBy('sort','desc') -> where('type','1') -> limit('5') -> get();
		return response() -> json($data);
	}

	//获取电影，会员
	public function getFilmAndMember($protype_id){
		$data = Course::select('course.id','course.course_name','course.description','course.cover_img') -> leftJoin('profession','profession_id','=','profession.id') -> leftJoin('protype','profession.protype_id','=','protype.id') -> where('protype.id',$protype_id) -> orderBy('course.sort','desc')  -> limit('6') -> get();
		foreach($data as $key => $value){
			$data[$key]['employmentSalary'] = rand(1,9).','.rand(100,999);
		}
		return response() -> json($data);
	}

	//获取剧集,综艺,培训课堂
	public function getSitcom($protype_id){
		$data = Profession::orderBy('sort','desc') -> select('id','pro_name') -> with('rel_course') -> where('protype_id',$protype_id) -> limit(6) -> get();
		foreach($data as $key => $value){
			foreach($data[$key]['rel_course'] as $k => $v){
				$data[$key]['rel_course'][$k]['learndCount'] = $v['click_num'];
			}
		}
		return response() -> json($data);
	}


	//推荐直播
	public function listByIndex(){
		$list = Performer::orderBy('sort','desc') -> select('id','avatar_img','performer_name') -> where('is_live','1') -> limit(10) -> get();
		return response() -> json($list);
	}

    //--获取直播列表--
    public function getLiveList(){
    	//获取数据操作
    	$data = Live::orderBy('sort','desc') -> where('status','1') -> get() -> toArray();
    	//循环处理
    	foreach ($data as $key => $value) {
    		//开始直播时间处理	03/24 20:00
    		$data[$key]['start_at'] = date('m/d H:i',$value['begin_at']);
    		//判断直播状态
    		if(time() < $value['begin_at']){
    			$data[$key]['live_status'] = '未直播';
    		}
    		if($value['begin_at'] <= time() && time() <= $value['end_at']){
    			$data[$key]['live_status'] = '直播中';
    		}
    		if($value['end_at']	< time()){
    			$data[$key]['live_status'] = '已结束';
    		}
    	}
    	//返回数据
    	return response() -> json($data);
    }

    //--获取专业列表的控制器--
    public function getProList(){
        //获取数据
        $data = Profession::orderBy('sort','desc') -> get() -> toArray();
        //打折
        foreach ($data as $key => $value) {
            $data[$key]['discount'] = $value['price'] * 0.01;
        }
        //返回数据
        return response() -> json($data);
    }



	public function isAlive(){
		$user = Auth::guard('home') -> user();
		if(empty($user) == true){
			$data = array(
					'errorMessage' => '尚未登录！',
					'success'      => false,
			);

		}else{
			$data = array(
				'success' => true,
				'resultObject' => [
					'id' => Auth::guard('home') -> user() -> id,
					'smallHeadPhoto' => Auth::guard('home') -> user() -> avatar,
				],
			);
		}
		return response() -> json($data);

	}

	public function getIndexPopup(){

	}

	//获取页面元素
	public function getPageMetadata(){
		$data = array(
			'errorMessage' => null,
			'resultObject' => array(
				'description' => '零玖一旗下布丁视频',
				'keywords'    => '零玖一，布丁视频',
				'pixelText'   => '零玖一，布丁视频，像素文本',
				'title'       => '布丁电影网',
			),
			'success'      => true,
		);
		return response() -> json($data);
	}

	//顶部消息
	public function findNewestNotice(){
		if(Auth::guard('home') -> user() == null){
			$data = array(
				'errorMessage' => null,
				'resultObject' => null,
			);
		}else{
			$data = array(
					'errorMessage' => null,
					'resultObject' => array(
							'id'             => 2,
							'infoType'       => 0,
							'notice_content' => '使用布丁电影网账号注册零玖一商城即可得200积分！<a href="http://www.lingjiuyi.cn/Public/register/AccountNumberParameter/budingwang" style="">点我注册</a>',
					),
					'success'      => true,
			);
		}
		return response() -> json($data);
	}

	public function careerPathList(Request $request){
		$data = array(
			'errorMessage' => null,
			'resultObject' => array(
				'0' => array(
					'careerPathName' => 'JavaEE工程师',
					'id' => 1,
				),
			),
			'success'      => true,
		);
		return response() -> json($data);
	}

	//搜索
	public function search(){
		return view('home.index.search');
	}

	//搜索
	public function courseSearch($pageNumber,$keyword,$searchCourseBelong,$pageSize){
		$offset = ($pageNumber - 1) * $pageSize;
		$lession = Lession::select('id','lession_name','description','cover_img','price','del_price','free','courseBelong') -> orderBy('sort','desc') -> where("lession_name","like","%$keyword%") -> where('status','2') -> offset($offset)-> limit($pageSize) -> get();
		$totalCount = Lession::select('id') -> where("lession_name","like","%$keyword%") -> count();
		$totalPageCount = ceil($totalCount/$pageSize);
		$page = array(
			'pageSize'       => $pageSize,         //每页显示条数
			'totalPageCount' => $totalPageCount,   //总页数
			'currentPage'    => $pageNumber,       //当前页
			'totalCount'     => $totalCount,       //总条数
		);
		$data = compact('lession','page');
		return response() -> json($data);

	}

	//首页购物车数量
	public function getCartNum(){
		$uid = Auth::guard('home') -> user() -> id;
		$num = Member_cart::where("member_id",$uid) -> count();
		$data = [
			'success' => true,
			'resultObject' => $num,
		];
		return response() -> json($data);
	}

	//首页未读消息总数
	public function getMessageCount(){
		$uid = Auth::guard('home') -> user() -> id;
		$num = Member_cart::where("member_id",$uid) -> count();
		$data = [
				'success' => true,
				'resultObject' => $num,
		];
		return response() -> json($data);
	}

	public function douban(){
		return view('home.index.douban');
	}

	//获取豆瓣分类tag
	public function getDirectionsDouban(){
		$type = Input::get('type');
		$url = "https://movie.douban.com/j/search_tags?type=";
		if($type == 'movie'){
			$url .= "movie";
		}elseif($type == 'tv'){
			$url .= "tv";
		}
		$req = $this -> curl_request($url);
		$res = json_decode($req,true);
		return response() -> json($res['tags']);
	}

	//获取豆瓣列表
	public function getMicroCoursesDouban(){
		$type = Input::get('type');
		$tag = Input::get('tag');
		$sort = Input::get('orderType') == 0 ? 'rank' : (Input::get('orderType') == 1 ? 'time' : 'recommend');
		$PageNumber = Input::get('pageNumber');
		$page_limit = Input::get('pageSize');
		$page_start = ($PageNumber - 1) * $page_limit;
		$url = "https://movie.douban.com/j/search_subjects?type=$type&tag=$tag&sort=$sort&page_limit=$page_limit&page_start=$page_start";
		$req = $this -> curl_request($url);
		$res = json_decode($req,true);
		$data = array(
			'resultObject' => $res['subjects'],
			'page' => [
				'currentPage' => $PageNumber,
				'totalPageCount' => 10,
			],
		);
		return response() -> json($data);
	}

	//获取豆瓣详情
	public function getMicroCoursesDetailDouban(){
		$id = Input::get('id');
		$type = Input::get('type');
		if($type == 'movie'){
			$url = "https://api.douban.com/v2/$type/$id";
		}elseif($type == 'tv'){
			$url = "https://movie.douban.com/j/subject_abstract?subject_id=".$id;
		}
		$req = $this -> curl_request($url);
		$res = json_decode($req,true);
		$full = $this -> getFull($id,$type);
		return response() -> json(compact('res','full'));
	}

	//获取豆瓣详情2
	public function getFull($id,$type){
		$html = $this -> curl_request("https://movie.douban.com/subject/".$id.'/');
		$crawler = new Crawler($html);
		//剧情简介
		$indent = $crawler -> filterXPath('//div[@id="link-report"]') -> filter('span') -> text();
		//影人
		$celebrities['img'] = $crawler -> filterXPath('//div[@id="celebrities"]/ul/li') -> each(function(Crawler $node, $i){
			$zaidouban = "https://img3.doubanio.com/f/movie/14960825e118267b5857fc0ae9f306ef8c74da8f/pics/movie/has_douban@2x.png";
			$img1 = substr($node -> filter('a') -> filter('div') -> attr('style'),22,103);
			$img2 = substr($node -> filter('a') -> filter('div') -> attr('style'),22,-1);
			return $img1 == $zaidouban ? substr($node -> filter('a') -> filter('div') -> attr('style'),132,-1) : $img2;
		});
		$celebrities['name'] = $crawler -> filterXPath('//div[@id="celebrities"]/ul/li') -> each(function(Crawler $node, $i){
			return $node -> filter('div') -> filter('span') -> filter('a') -> text();
		});
		$celebrities['role'] = $crawler -> filterXPath('//div[@id="celebrities"]/ul/li') -> each(function(Crawler $node, $i){
			return $node -> filter('div') -> filter('span') -> last() -> text();
		});
		//视频及图片
		if($type == 'tv'){
			$related_pic = $crawler -> filterXPath('//div[@id="related-pic"]/ul/li') -> each(function(Crawler $node, $i){
				$src = $node -> filter('a') -> attr('class') == 'related-pic-video' ? '' : $node -> filter('a') -> filter('img') -> attr('src') ;
				return $src;
			});
		}elseif($type == 'movie'){
			$related_pic = $crawler -> filterXPath('//div[@id="related-pic"]/ul/li') -> each(function(Crawler $node, $i){
				return $node -> filter('a') -> text() == ""  ? $node -> filter('a') -> filter('img') -> attr('src') : '' ;
			});
		}
		//短评
		$hot_comments['comment_name'] = $crawler -> filterXPath('//div[@id="hot-comments"]/div') -> each(function(Crawler $node, $i){
			return $node -> filterXPath('//div[@class="comment"]') -> filter('h3') -> filterXPath('//span[@class="comment-info"]') -> filter('a') -> text();
		});
		$hot_comments['comment_time'] = $crawler -> filterXPath('//div[@id="hot-comments"]/div') -> each(function(Crawler $node, $i){
			return $node -> filterXPath('//div[@class="comment"]') -> filter('h3') -> filterXPath('//span[@class="comment-info"]') -> filterXPath('//span[@class="comment-time "]') -> attr('title');
		});
		$hot_comments['comment_content'] = $crawler -> filterXPath('//div[@id="hot-comments"]/div') -> each(function(Crawler $node, $i){
			return $node -> filterXPath('//div[@class="comment"]') -> filter('p') -> text();
		});
		//剧评
		$review_list['avator'] = $crawler -> filterXPath('//div[@class="review-list  "]/div') -> each(function(Crawler $node, $i){

			return $i <9 ? $node -> filter('div') -> filter('header') -> filterXPath('//a[@class="avator"]') -> filter('img') -> attr('src') : '';
		});
		$review_list['name'] = $crawler -> filterXPath('//div[@class="review-list  "]/div') -> each(function(Crawler $node, $i){
			return $i <9 ? $node -> filter('div') -> filter('header') -> filterXPath('//a[@class="name"]') -> text() : '';
		});
		$review_list['time'] = $crawler -> filterXPath('//div[@class="review-list  "]/div') -> each(function(Crawler $node, $i){
			return $i < 9 ? $node -> filter('div') -> filter('header') -> filterXPath('//span[@class="main-meta"]') -> text() : '';
		});
		$review_list['title'] = $crawler -> filterXPath('//div[@class="review-list  "]/div') -> each(function(Crawler $node, $i){
			return $i < 9 ? $node -> filter('div') -> filter('div') -> filter('h2') -> filter('a') -> text() : '';
		});
		$review_list['short'] = $crawler -> filterXPath('//div[@class="review-list  "]/div') -> each(function(Crawler $node, $i){
			return $i < 9 ? $node -> filter('div') -> filter('div') -> filter('div') -> filter('div') -> eq(0) -> text() : '';
		});
		$data = compact('indent','celebrities','related_pic','hot_comments','review_list');
		return $data;
	}

	public function curl_request($url, $post = false, $data = array(), $https = false){
		$ch = curl_init($url);//A、使用curl_init函数初始化curl请求(设置请求地址)
		curl_setopt($ch, CURLOPT_REFERER, "https://movie.douban.com");
		//curl_setopt($ch,CURLOPT_SAFE_UPLOAD,false);//关闭上传文件安全验证功能，在php5.6以前是关闭的
		if($post)
		{//判断post请求
			curl_setopt($ch, CURLOPT_POST, true);// B、使用curl_setopt函数配置curl请求(设置请求方式请求参数等)//设置请求方式
			curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//设置请求参数
		}
		if($https)
		{ //https协议请求 默认发送http协议的请求，如果是https的请求，需要做以下设置
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //检测ssl证书 这里是禁用检测
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //检测ssl证书和域名匹配 这里是禁用检测
		}
		// C、使用curl_exec函数发送curl请求
		//默认返回true|false  如果需要获取请求的执行结果，需要设置CURLOPT_RETURNTRANSFER
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//如果不设置，默认直接输出执行结果
		$result = curl_exec($ch);
		curl_close($ch); // D、请求结束使用curl_close函数关闭curl请求，释放资源
		return $result;//返回结果给调用方
	}

	public function testA(){
		$url = 'https://aip.baidubce.com/oauth/2.0/token';
		$post_data['grant_type']    = 'client_credentials';
		$post_data['client_id']     = 'TmOkpjAPDxETwt4rkQnSa0WI';
		$post_data['client_secret'] = 'LfEQnABqdv3YGDKAeRKN7SzGYGKHD10E';
		$o = "";
		foreach ( $post_data as $k => $v )
		{
			$o.= "$k=" . urlencode( $v ). "&" ;
		}
		$post_data = substr($o,0,-1);

		$res = $this -> curl_request($url, true, $post_data);
		$res = json_decode($res,true);

		$url = "https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general?access_token=".$res['access_token'];
		$image = "";
		$post_data = [
			'image' => $image
		];

		$result = $this -> curl_request($url, true, $post_data);
		$result = json_decode($result,true);
		dump($result);



	}

	public function testB(){
		$html = <<<'HTML'
<!DOCTYPE html>
<html>
        <body>
        <p class="message">Hello World!</p>
        <p class="msg">Hello Crawler!</p>
        <div class="ys"><a href="/gen"><img src="/img/img.png" alt="暂无图片"></a></div>
        </body>
</html>
HTML;
		$crawler = new Crawler($html);
		foreach ($crawler as $domElement)
		{
			dump($domElement->nodeName); //string(4) "html"
		}
		echo $crawler->filterXPath('//body/p')->text(); //Hello World!
		echo '1<hr/>';
		echo $crawler->filterXPath('//body/p')->last()->text(); //Hello Crawler!
		echo '2<hr/>';
		dump($crawler->filterXPath('//body')->html()); //string(86) "Hello World!Hello Crawler!"
		echo '3<hr/>';
		foreach ($crawler->filterXPath('//body/p') as $i => $node) {
			$c = new Crawler($node);
			echo '<br/>';
			echo $c->filter('p')->text();
		}
		echo '4<hr/>';
		$nodeValues =
				$crawler->filterXPath('//body/p')->each(function (Crawler $node, $i) {
     				return $node->text();
				});
		dump($nodeValues);
		echo $crawler->filterXPath('//body/p')->attr('class');
		echo '5<hr/>';
		echo $crawler->filterXPath('//div[@class="ys"]')->filter('a')->attr('href');
		echo '6<hr/>';
		dump($crawler->filterXPath('//div[@class="ys"]')->filter('a>img')->extract(array('alt', 'src')));
		echo '7<hr/>';

		//$html = $this->curl_request("https://movie.douban.com/subject/26985973/");
		//dump($html);

	}

	public function testC(){
//		$post_data = [
//			'apiTocken' => '338015277495131485a659e12c13de10d7861',
//			'goods_number' => 1,
//			'item_id' => 11200,
//		];
//		for($i = 0 ; $i <= 5; $i++){
//			$res[] = $this -> curl_request("http://sjsc.v-town.cc/transaction/create_order",true,$post_data);
//		}
//		dump($res);
	}

	public function testD(){
		// 建立一个指向新COM组件的索引
		$word = new COM("word.application") or die("无法打开 MS Word");
	}

}
